<script lang='ts' setup>
import { ref, watch } from 'vue';
import SqlEditor from '@/components/SqlEditor/index.vue'
import MonacoEditor from "@/components/MonacoEditor/index.vue"
import { ElMessage } from 'element-plus';
import { actionType } from '@/utils/commonData';
const sqlEditorRef = ref()
const props = defineProps<{
  detail: any
  type: string
  tableName: string
}>();
const emit = defineEmits<{
  (e: 'onChange', val: any): void
}>();
const scriptData = ref()

const diScript = ref<string>('')

const dialogVisible = ref(false)

function handleClose() {
  dialogVisible.value = false;
}


function handleConfirm() {
  dialogVisible.value = false;
  // 编辑脚本，显示编辑器的内容
  if (props.type != 'CustomScript') {
    let scriptDataRaw = sqlEditorRef.value.onChange()
    emit('onChange', scriptDataRaw)
  }
  //自定义脚本，显示自定义编辑器的内容
  if (props.type == 'CustomScript') {
    emit('onChange', { actionType: 'customScript', saveScript: diScript.value })
  }

}



function openDia() {
  if (!props.type) {
    ElMessage.error('请先选择方法类型')
    return
  } 
  if (!props.tableName) {
    ElMessage.error('请先填写表名')
    return
  } 
  dialogVisible.value = true
}
watch(() => [props.detail, props.type], () => {
  scriptData.value = JSON.parse(JSON.stringify(props.detail))
  scriptData.value.actionType = actionType.find((item: any) => item.value == props.type)?.mapToEditor as string
  if (scriptData.value.actionType == ('delete')) {
    scriptData.value.physicsDelete = actionType.find((item: any) => item.value == props.type)?.isRealDelete as boolean
  }
  if (scriptData.value.actionType == 'customScript') {
    scriptData.value = {
      saveScript: scriptData.value?.saveScript as string,
      actionType: 'customScript'
    }
  }
  if (scriptData.value) {
    diScript.value = scriptData.value.saveScript as string
  } else {
    diScript.value = ''
  }
}, {
  immediate: true,
  deep: true
})


</script>
<template>
  <div style="width:100%;">
    <el-button type="primary" link icon="Edit" @click="openDia">编辑脚本</el-button>
  </div>
  <!-- 脚本弹窗 -->
  <el-dialog v-model="dialogVisible" title="编辑脚本" width="80%" @close="handleClose" destroy-on-close>
    <sql-editor v-if="type != 'CustomScript'" :table-name="tableName" :back-data="scriptData" ref="sqlEditorRef" />
    <monaco-editor v-else v-model="diScript" language="txt" style="height:600px;" />
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleConfirm">保存编辑</el-button>
    </template>
  </el-dialog>
</template>
<style scoped lang='scss'></style>